import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/model/car/car_cate_model.dart';
import 'package:flutter_yres/model/car/car_merchant_entity.dart';
import 'package:jlocation/jlocation.dart';
import 'package:flutter_yres/tool/star.dart';
import 'package:flutter_yres/pages/car/merchant_detail.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CarSubPage extends StatefulWidget {
  String pdd_id;
  String name;
  String auth;
  
  CarSubPage({Key key, this.pdd_id,this.name,this.auth}) : super(key: key);

  @override
  _CarSubPageState createState() => _CarSubPageState(pdd_id);
}

class _CarSubPageState extends State<CarSubPage> {
  String pdd_id;
  _CarSubPageState(this.pdd_id);
  EasyRefreshController _controller = new EasyRefreshController();
  List<CarCateModelData> subs = []; 
  int page = 1;
  var search = '';
   List<CarMerchantModelData> merchants = []; //商户列表

  double _listHeight = ScreenUtil.getInstance().setHeight(240); //单个列表高度

double lat, lng;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
     appBar: AppBar(
          title: Text(widget.name),
        ),
      body:Container(
      color: Colors.white,
      child: _buildSub(),
    )
    ) ;
  }

  //其他类别主页内容
  Widget _buildSub() {
    return Container(
      child: new EasyRefresh(
        //刷新  加载组件
        controller: _controller,
        child: CustomScrollView(slivers: <Widget>[
          SliverGrid(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: (ScreenUtil.getInstance().setWidth(750) - ScreenUtil.getInstance().setWidth(20)) / 5,
              mainAxisSpacing: 8.0,
              crossAxisSpacing: 10.0,
              childAspectRatio: 0.9, //子控件宽高比
            ),
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                return _itemBuilder(context, subs[index]);
              },
              childCount: subs.length,
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
                height: ScreenUtil.getInstance().setHeight(60),
                child: Column(
                  children: <Widget>[
                    // _buildPopHeader()
                    ],
                )),
          ),
          SliverFixedExtentList(
              delegate: SliverChildBuilderDelegate(_buildListItem,
                  childCount: merchants.length),
              itemExtent: _listHeight),
        ]),
        onRefresh: () async {
          page = 1;
          getList();
        },
        onLoad: () async {
          page++;
          getList();
        },
      ),
    );
  }

  Widget _itemBuilder(BuildContext context, item) {
    return InkWell(
      onTap: () {
        // print(item.name);
        // setState(() {
        //   page = 1;
        //   search = item.name;
        //   getPDDShopList();
        // });
      },
      child: Column(
        children: <Widget>[
          Container(
            height: ScreenUtil.getInstance().setWidth(20),
          ),
          Image.network(
            Api.BaseUrl + item.icon,
            width: ScreenUtil.getInstance().setWidth(85),
          ),
          Text(item.name,
              style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(26)), maxLines: 1, overflow: TextOverflow.ellipsis),
        ],
      ),
    );
  }

//条件筛选头部
  _buildPopHeader() {
    return Container(
      height: ScreenUtil.getInstance().setHeight(60),
      width: ScreenUtil.getInstance().setWidth(750),
      child: Row(
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "综合",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(25),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "销量",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "价格",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(28)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "佣金",
                            style: TextStyle(fontSize: ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
        ],
      ),
    );
  }

  Widget _buildListItem(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {
          //处理点击事件
          CarMerchantModelData model = merchants[index];
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) => MerchantDetailPage(
                        model: model,
                      ) //打开第二个页面，并传值，传递值的名称是model
                  ));
        },
        child: Container(
            margin: EdgeInsets.fromLTRB(0, ScreenUtil.getInstance().setHeight(15), 0, 0),
            child: Column(
              children: <Widget>[
                Row(children: <Widget>[
                  _leftImage(index),
                  Expanded(
                    child: _rightColumn(index),
                  )
                ], crossAxisAlignment: CrossAxisAlignment.start),
                Divider(
                  height: 1,
                )
              ],
            )));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(l) ?? 0,
            ScreenUtil.getInstance().setHeight(t) ?? 0,
            ScreenUtil.getInstance().setWidth(r) ?? 0,
            ScreenUtil.getInstance().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage(int index) {
    //左图
    var image = Container(
      child: merchants[index].merchant_avatar == null
          ? Image.asset('images/pic_default.png')
          : new Image(
              image: NetworkImage(merchants[index].merchant_avatar),
              width: ScreenUtil.getInstance().setHeight(150),
              height: ScreenUtil.getInstance().setHeight(150),
              fit: BoxFit.fill),
      color: Colors.grey,
    );
    return _pd(image, l: 20, t: 0, r: 5, b: 40);
  }

  Widget _rightColumn(int index) {
    //右内容
    var title = Text(
      merchants[index].merchant_name,
      style: TextStyle(color: Colors.black, fontSize: 16.0),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    var score = RichText(
      text: TextSpan(style: TextStyle(color: Colors.grey), children: [
        TextSpan(
            text: merchants[index].comment_score + '分',
            style: TextStyle(fontSize: 15.0)),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var distance = RichText(
      text: TextSpan(style: TextStyle(fontSize: 13.0), children: [
        TextSpan(
            text: '¥' + merchants[index].consumption + '/人',
            style: TextStyle(color: Colors.grey)),
        TextSpan(text: '导航', style: TextStyle(color: Colors.orange)),
      ]),
    );
    var address = Text(
      // merchants[index].province +
      merchants[index].city +
          merchants[index].county +
          merchants[index].detail_address,
      style: TextStyle(color: Colors.grey, fontSize: 13.0),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    return new Column(
      children: <Widget>[
        _pd(title, l: 8, t: 0, r: 10, b: 8),
        Row(
          children: <Widget>[
            _pd(
                new StaticRatingBar(
                  size: 15.0,
                  rate: double.parse(merchants[index].comment_score),
                ),
                l: 8,
                t: 0,
                r: 0,
                b: 0),
            _pd(score, l: 8, t: 0, r: 8, b: 0),
            distance
          ],
        ),
        Row(
          children: <Widget>[
            _pd(
                Image.asset(
                  'images/icon_nav_location.png',
                  width: 13,
                  height: 15,
                  fit: BoxFit.fill,
                ),
                l: 0,
                t: 0,
                r: 0,
                b: 0),
            _pd(address, l: 10, t: 0, r: 10, b: 0),
          ],
        ),
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  @override
  void initState() {
    getPDDSubCatList(this.pdd_id);
    super.initState();
  }

/*汽车子级列表*/
  getPDDSubCatList(String pid) async {
    FormData data = new FormData.fromMap({'pid': pid});
    Response<String> response =
        await HttpUtil().post(Api.GetSubListByParentUrl, data: data);
    Map userMap = json.decode(response.data);
    print(userMap);
    CarCateModelEntity itemEntity = new CarCateModelEntity.fromJson(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
           subs.clear();
          subs = itemEntity.data;
          // getList();
        });
      }
    }
  }

 getLocation() {
   print('定位啊=========');
    var loc = new Jlocation();
    // loc.onLocationChanged().listen((loc) {
    //   setState(() {
    //     if (!mounted) return;
    //     lat = loc.latitude;
    //     lng = loc.longitude;
    //     getList();
    //   });
    // });
    getList();
  }

  getList() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    //加油站
    FormData data;
    if (lat == null) {
      FormData data = new FormData.fromMap({
        'distinct': 10,
        'page': page.toString(),
        'auth':widget.auth,
        'per': '8',
      });
    } else {
      data = new FormData.fromMap({
        'lng_lat': lng.toString() + "," + lat.toString(),
        'distinct': '10',
        'page': page.toString(),
        'auth':widget.auth,
        'per': '8',
      });
    }
    // print(data);
    Response<String> response =
        await HttpUtil().post(Api.GetMerchantListUrl, data: data);
    Map userMap = json.decode(response.data);
    CarMerchantModelEntity jyzEntity =
        new CarMerchantModelEntity.fromJson(userMap);
    print('=====商户列表');
    if (jyzEntity.code == 1) {
      print(userMap);
      if (mounted) {
        setState(() {
          if (page == 1) {
            merchants.clear();
            merchants = jyzEntity.data;
          } else {
            merchants.addAll(jyzEntity.data);
          }
        });
      }
    }

    // FormData data = new FormData.fromMap({'page': page, 'keyword': search});
    // Response<String> response =
    //     await HttpUtil().post(Api.GetPddGoodsListUrl, data: data);
    // Map userMap = json.decode(response.data);
    // PddListModelEntity itemEntity = new PddListModelEntity.fromJson(userMap);
    // // print(userMap);
    // if (itemEntity.code == 0) {
    //   if (mounted) {
    //     setState(() {
    //       if (page == 1) {
    //         shopData.clear();
    //         shopData = itemEntity.data;
    //       } else {
    //         shopData.addAll(itemEntity.data);
    //       }
    //     });
    //   }
    // }
  }
}
